package com.ant.gprnter.flutter_gprinter

import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock

class PrintTaskQueue {
    private val executorService: ExecutorService = Executors.newSingleThreadExecutor()
    private val lock: Lock = ReentrantLock()
    private val condition: Condition = lock.newCondition()
    private val paused = AtomicBoolean(false)
    private val queue = ArrayDeque<PrintTask>()

    init {
        loop()
    }

    private fun loop() {
        System.out.println("start loop")
        executorService.submit {
            lock.lock()
            try {
                while (true) {
                    if (paused.get()) {
                        condition.await()
                    }
                    if (queue.size == 0) {
                        disconnectPrint()
                        condition.await()
                    }
                    val  task = queue.last()
                    print(task)
                }
            } catch (e: InterruptedException) {
                // 处理中断异常，例如可以记录日志或者采取其他恢复措施
                e.printStackTrace()
            } finally {
                lock.unlock()
            }
        }
    }

    private fun print(task: PrintTask) {
        System.out.println("start loop ${task.connectInfo}")
        Thread.sleep(2000)
    }

    private fun disconnectPrint() {
        TODO("Not yet implemented")
    }

    fun submit(task: PrintTask) {
        queue.add(task)
        resume()
    }

    fun pause() {
        lock.lock()
        try {
            paused.set(true)
        } finally {
            lock.unlock()
        }
    }

    fun resume() {
        lock.lock()
        try {
            paused.set(false)
            condition.signalAll()
        } finally {
            lock.unlock()
        }
    }

    fun shutdown() {
        executorService.shutdown()
    }


}